import { Actionable } from '@/desktop/components'
import FileSendPreview, { type PreviewingInfo } from '@/desktop/components/FileSendPreview'
import { useOwner } from '@/desktop/logics/chat/info'
import { useChatNotications } from '@/desktop/logics/chat/notifications'
import { useDropFiles } from '@/desktop/logics/handle-drop-files'
import ChatSidebars from '@/desktop/views/chat-sidebars'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { type ChatRecordType } from '@/services/contact-chat'
import type { ContactWithTransfer } from '@/services/contacts'
import { BatchSendHandling } from './batch-send'
import { ChatEditor } from './editor'
import { ChatRecords } from './records'
import { ChatTitle } from './title'

export default function Chat() {
  const [current] = useStreams(services.contacts.current.contact)
  return !current ? (
    <div css={styles.placeholder}>选择左侧联系人，发送消息</div>
  ) : (
    <Content contact={current} />
  )
}

function Content(props: { contact: ContactWithTransfer }) {
  const { contact } = props

  useChatNotications()
  const owner = useOwner(contact)

  const [sendPreviewing, setSendPreviewing] = useState<PreviewingInfo | null>(null)
  const sendFiles = useCallback(
    (files: File[], autoStart?: boolean, recordType?: ChatRecordType) =>
      setSendPreviewing({ files, autoStart, recordType, onFinish }),
    [],
  )
  const { props: dragToSendProps } = useDropFiles(sendFiles)

  const onFinish = useCallback(() => setSendPreviewing(null), [])

  // 部分组件需要在切换联系人时重置状态，通过设置 key 来快速实现此效果，免去了复杂的状态处理
  return <>
    <div css={styles.chatContainer} {...dragToSendProps}>
      <ChatTitle contact={contact} owner={owner} />
      <ChatRecords key={contact.id} contact={contact} owner={owner} />
      <Actionable>
        <ChatEditor key={contact.id} contact={contact} sendFiles={sendFiles} />
      </Actionable>
    </div>
    <ChatSidebars />
    <FileSendPreview previewing={sendPreviewing} />
    <BatchSendHandling />
  </>
}

const styles = {
  placeholder: css`
    color: rgba(85, 85, 85, 0.65);
    flex: 1;
    font-size: 18px;
    padding-top: 40vh;
    text-align: center;
  `,

  chatContainer: css`
    border-left: 1px solid #f0f0f0;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;
    z-index: 1;
  `,
}
